package com.frank.libandroid;

import androidx.lifecycle.Observer;

import okhttp3.ResponseBody;

public abstract class HttpCallback<T> implements Observer<HttpResult> {
    public static HttpConverter converter;
    public static ErrorHandler errorHandler;

    public interface ErrorHandler {
        void onError(int errorCode, String errorMessage);
    }

    @Override
    public void onChanged(HttpResult httpResult) {
        if (httpResult.isSuccessful) {
            onResponseBody(httpResult.responseBody);
        } else {
            onError(httpResult.errorCode, httpResult.errorMessage);
        }
    }

    protected void onResponseBody(ResponseBody responseBody) {
        T convert = null;
        convert = converter.convert(responseBody, this);
        if (convert != null) {
            onSuccess(convert);
        }
    }

    protected abstract void onSuccess(T t);

    public void onError(int errorCode, String errorMessage) {
        if (errorHandler != null) {
            errorHandler.onError(errorCode, errorMessage);
        }
    }
}
